/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: PushHttpUtils.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	20 Jul,2015
 */
package com.sirdc.modules.push.util;

import java.security.MessageDigest;
import java.util.Map;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

import org.apache.commons.codec.binary.Hex;

import com.sirdc.modules.push.entity.SdkHttpResult;

/**
 * 
 * @version Revision: 0.0.1
 * @Date: 20 Jul,2015
 */
public class PushHttpUtils {

	private static final String APPKEY = "RC-App-Key";
	private static final String NONCE = "RC-Nonce";
	private static final String TIMESTAMP = "RC-Timestamp";
	private static final String SIGNATURE = "RC-Signature";
	
	/**
	 * 创建post请求对象
	 * @author: weihuang.peng
	 * @param appKey
	 * @param appSecret
	 * @param uri
	 * @return
	 */
	public static SdkHttpResult sendPost(String appKey, String appSecret, String uri, Map<String, Object> formMap) {
		String nonce = String.valueOf(Math.random() * 1000000);
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
		String sign = hexSHA1(toSign.toString());
		
		HttpRequest request = HttpRequest.post(uri);
		request.timeout(30000);
		request.header(APPKEY, appKey);
		request.header(NONCE, nonce);
		request.header(TIMESTAMP, timestamp);
		request.header(SIGNATURE, sign);
		request.header("Content-Type", "application/x-www-form-urlencoded");
		
		if (formMap != null) {
			request.form(formMap);
		}
		
		HttpResponse resp = request.send();
		return returnResult(resp);
	}
	
	/**
	 * 转换返回的结果
	 * @param resp
	 * @return
	 */
	public static SdkHttpResult returnResult(HttpResponse resp) {
		int code = resp.statusCode();
		String result = resp.body();
		return new SdkHttpResult(code, result);
	}
	
	public static String hexSHA1(String value) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(value.getBytes("utf-8"));
			byte[] digest = md.digest();
			return byteToHexString(digest);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public static String byteToHexString(byte[] bytes) {
		return String.valueOf(Hex.encodeHex(bytes));
	}
}
